<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @current-change="handleCurrentChange"  :page-size="pageSize" :total="total" v-on:click="getProducts">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="warning" @click="onsale" :disabled="this.sels.length===0">上架</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="danger" @click="offsale" :disabled="this.sels.length===0">下架</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="products" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="服务名称" width="150" sortable>
			</el-table-column>
			<el-table-column prop="saleprice" label="售价" width="80"  sortable>
			</el-table-column>
			<el-table-column prop="onsaletime" label="上线时间" width="150" sortable>
			</el-table-column>
			<el-table-column prop="offsaletime" label="下线时间" width="150" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100"  sortable>
				<!--这里我们给状态定义一个颜色为了视觉效果更好，经测试只能写在这里，和下面的操作一样
                scope.row是拿到当前行的值-->
				<template scope="scope">
					<span style="color: green" v-if="scope.row.state==1">已上架</span>
					<span style="color: red" v-else="scope.row.state==0">已下架</span>
				</template>
			</el-table-column>
			<el-table-column prop="costprice" label="成本价" width="100" sortable>
			</el-table-column>
			<el-table-column prop="salecount" label="销售数量" width="100" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" :current-page="page" @current-change="handleCurrentChange"  :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog destroy-on-close :title="title" :visible.sync="productFormVisible" :close-on-click-modal="false">
			<el-form :model="productForm" label-width="120px" :rules="productFormRules" ref="productForm">
				<el-form-item label="服务名称" prop="name">
					<el-input v-model="productForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="售价" prop="saleprice">
					<el-input v-model="productForm.saleprice" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="成本" prop="costprice">
					<el-input v-model="productForm.costprice" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="资源" prop="resources">
					<!--<el-input v-model="productForm.resources" auto-complete="off"></el-input>-->
					<el-upload
							class="upload-demo"
							action="http://localhost:8080/fastDfs"
							:on-preview="handlePreview"
							:on-remove="handleRemove"
							:on-success="handleSuccess"
							:file-list="fileList"
							list-type="picture">
						<el-button size="small" type="primary">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
					</el-upload>
				</el-form-item>
				<el-form-item label="简介" prop="detail.intro">
					<!--<el-input v-model="productForm.detail.intro" auto-complete="off"></el-input>-->
					<quill-editor
							v-model="productForm.detail.intro"
							:options="quillOption"
					>
					</quill-editor>
				</el-form-item>
				<el-form-item label="预约须知" prop="detail.orderNotice">
					<!--<el-input v-model="productForm.detail.orderNotice" auto-complete="off"></el-input>-->
					<quill-editor
							v-model="productForm.detail.orderNotice"
							:options="quillOption"
					>
					</quill-editor>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="productFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="productLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>

    import { quillEditor } from "vue-quill-editor"; //调用编辑器
    import 'quill/dist/quill.core.css';
    import 'quill/dist/quill.snow.css';
    import 'quill/dist/quill.bubble.css';
    import quillConfig from '../../common/js/quill-config';
	export default {
        components: {
            quillEditor
        },
		data() {
			return {
			    quillOption:quillConfig,
                fileList:[],
				filters: {
					keyword: ''
				},
                response:{
                    resultObj:''
                },
                resources:'',
                products: [],
				total: 0,
				page: 1,
                pageSize:10,
				listLoading: false,
				sels: [],//列表选中列

				productFormVisible: false,//编辑界面是否显示
				productLoading: false,
				productFormRules: {
					email: [
						{ required: true, message: '请输入邮箱', trigger: 'blur' }
					],
                    phone: [
                        { required: true, message: '请输入电话', trigger: 'blur' }
                    ],
                    username: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ]
				},
                title:"",
				//编辑界面数据
				productForm: {
                    id:null,
                    name: '',
                    costprice: 0,
                    saleprice: 0,
                    resources: '',
                    detail:{
                        id:null,
                        intro:'',
                        orderNotice:''
                    }

                },

			}
		},
		methods: {
            onsale(){
                var ids = this.sels.map(item => item.id);
                //获取选中的行
                if(!this.sels || this.sels.length  <1){
                    this.$message({ message: '老铁，你不选中数据，臣妾上架不了啊....',type: 'error'});
                    return;
                }
                this.$confirm('确认上架选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.post('/product/onsale',ids).then((res) => {
                        this.listLoading = false;

                        if(res.data.success){
                            this.$message({
                                message: '上架成功',
                                type: 'success'
                            });
                        }else{
                            this.$message({
                                message: res.data.message,
                                type: 'error'
                            });
                        }
                        this.getProducts();
                    });
                }).catch(() => {

                });
            },
            offsale(){

                var ids = this.sels.map(item => item.id);
                //获取选中的行
                if(!this.sels || this.sels.length  <1){
                    this.$message({ message: '老铁，你不选中数据，臣妾下架不了啊....',type: 'error'});
                    return;
                }
                this.$confirm('确认下架选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.post('/product/offsale',ids).then((res) => {
                        this.listLoading = false;

                        if(res.data.success){
                            this.$message({
                                message: '下架成功',
                                type: 'success'
                            });
                        }else{
                            this.$message({
                                message: res.data.message,
                                type: 'error'
                            });
                        }
                        this.getProducts();
                    });
                }).catch(() => {

                });
            },
            search() {
                //查询完，原来分页条件已经没用了，要跑到第一页去
                this.page = 1;
                this.getProducts();
            },

			handleCurrentChange(val) {
				this.page = val;
				this.getProducts();
			},

			//获取员工列表
			getProducts() {
				let para = {
					currentPage: this.page,
					pageSize:this.pageSize,
					keyword: this.filters.keyword
				};
				this.listLoading=true;
			  this.$http.post("/product",para)
                  .then(result=>{
                      result=result.data;
                      this.total=result.totals;
                      this.products=result.rows;
                      this.listLoading=false;
                  })
                  .catch(result=>{
                      alert("系统错误！")
                  })
			},
            handleSuccess(response, file, fileList){
                //上传图片成功了会跑到这，我们先定义一个空的变量用来装我们上传图片得路径
                let resources = '';
                //上传了图片我们才做保存，所以做一个非空判断
                if(fileList) {
                    //我们需要循环遍历将每一次放进来得值进行处理追加
                    for (let i=0;i<fileList.length;i++) {
                        //如果是最后一个我们就不追加“，”
                        if (i===fileList.length-1) {
                            resources+=fileList[i].response.resultObj;
                        }else {
                            //否则都要追缴“，”
                            resources+=fileList[i].response.resultObj+",";
                        }
                    }
                }
                //拼接地址为xx,yy,zz，赋值返回去
                this.productForm.resources =resources;
            },
            handleRemove(file, fileList) {
                console.log(file, fileList);
                //这里是为了取出路径中的后半截我们需要的才能删掉，之前在上传照片的时候多加了这个属性就是为了方便删除
                let path = file.response.resultObj;
                this.$http.delete("/fastDfs?path="+path)
                    .then(result=>{
                        result = result.data;
                        if(result.success){

                            let resources = '';
                            if(fileList){
                                for(let i=0;i<fileList.length;i++){
                                    //除了最后一个都要加逗号
                                    if(i==fileList.length-1){
                                        resources+=fileList[i].response.resultObj;
                                    }else{
                                        resources+=fileList[i].response.resultObj+",";
                                    }
                                }
                            }
                            //拼接地址为xx,yy,zz
                            this.productForm.resources =resources;
                            this.$message({
                                message: "删除成功!",
                                type: 'success'
                            });

                        }else{
                            this.$message({
                                message: result.message,
                                type: 'error'
                            });
                        }
                    })
            },
            handlePreview(file) { //预览
                console.log(file);
            },
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
                    //    由于后端的删除接口使根据resultful风格来编码的，所以我们这里要给他弄成相对应的风格
                    let url = "/product/"+row.id;
                    this.$http.delete(url)
                        .then(result=> {
                                result=result.data;//{sucess:false,message}
                                //去除忙等框
                                this.listLoading = false;

                                if (result.success) {
                                    //删除成功我们跳回第一页，防止有那一页还没数据继续停留的bug
                                    this.page=1;
                                    //提示
                                    this.$message({
                                        message: '删除成功',
                                        type: 'success'
                                    });
                                    //重新查找数据
                                    this.getProducts();
                                }else {
                                    //提示
                                    this.$message({
                                        message: result.message,
                                        type: 'error'
                                    });
                                    //重新查找数据
                                    this.getProducts();
                                }
                            }
                        )
                        .catch(result=>{
                            //去除忙等框
                            this.listLoading = false;
                            //提示
                            this.$message({
                                message: '系统错误',
                                type: 'error'
                            });
                        })
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
                //不管怎样，先清除图片，防止会展示重复图片
                this.fileList=[];
                this.title="编辑";
				this.productForm = Object.assign({}, row);

				//回显资源详情
                //先定义一个变量来存放需要回显得资源
                let resources = row.resources;

                //有资源的话就直接回显，要非空判断避免空指针
                if (resources) {
                    let resourceArr = resources.split(",")
                    for(let i=0;i<resourceArr.length;i++) {
                        //为了能回显可知必须传回对应的格式,在最后需要加上一个自定义属性，为了后面我们需要删除的时候可以直接通过属性名取出来
                        this.fileList.push({"name":"yhk.jpg",
                            "url":"http://115.159.217.249:8888"+resourceArr[i],
                            "response":{
                                "resultObj":resourceArr[i],
                            }
                        })
                    }
                }

				//我们编辑回显还要显示服务详情，所以我们需要再去发送一个请求去查询服务详情
                this.$http.get("/product/detail/"+row.id)//根据当前行的id去链表查找服务详情的数据
                    .then(result=>{
                        result = result.data; //ProductDetail
                        //如果能查寻到值我们直接赋值进去
                        if(result) {
                            this.productForm.detail = result;
                        }
                        //要等查完了数据我们才能让编辑框显示，不然会报错
                        this.productFormVisible = true;
                    })
                    .catch(result=>{
                        this.$message({
                            message: '系统错误',
                            type: 'error'
                        });
                        console.log("yhktest1" + result);
                    })
			},
			//显示新增界面
			handleAdd: function () {
                this.fileList=[];
			    this.title="新增";
				this.productForm = {//清空

                    id:null,
                    name: '',
                    resources:'',
                    saleprice:0,
                    costprice:0,
                    detail:{
                        id:null,
                        intro:'',
                        orderNotice:''
                    }

				};
                this.productFormVisible = true; //显示新增框
			},
			//保存
			save: function () {
                this.fileList=[],
				this.$refs.productForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '焜焜提示', {}).then(() => {
							this.productLoading = true;

						//	我们为了在下面做添加和修改，因为我们之前将数据双向绑定，所以我们对数据操作之前我们先拷贝一份数据
                            let para = Object.assign({}, this.productForm);
                            //我们发闪送请求到后台，直接保存数据
                            this.$http.put("/product",para)
                                .then(result=>{
                                    result=result.data;
                                    if (result.success){
                                        //成功就去除忙等狂
                                        this.productLoading = false;
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
                                        //重新获取数据
                                        this.getProducts();
                                    }else {
                                        //失败就去除忙等狂
                                        this.productLoading = false;
                                        this.$message({
                                            message: result.message,
                                            type: 'error'
                                        });
                                        //重新获取数据
                                        this.getProducts();
                                    }
                                    this.productFormVisible = false;
                                })
                                .catch(result=>{
                                    this.productLoading = false;
                                    this.productFormVisible = false;
                                    alert("系统错误")
                                })
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},

            //批量删除
            batchRemove: function () {
                //我们不需要toString，因为我们直接返回一个数组给后台进行遍历一个个删除
                var ids = this.sels.map(item => item.id);
                this.$confirm('确认删除选中记录吗？', '焜焜提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //传递数组参数到后台批量删除，不需要let para = { ids: ids };
                    this.$http.patch("/product",ids)
                        .then(result=>{
                            result = result.data;
                            //去除忙等框
                            this.listLoading = false;
                            if (result){
                                //成功提示
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.page =1; //删除后跳转第一页
                                //从新获取数据
                                this.getProducts();
                            }else {
                                //去除忙等框
                                this.listLoading = false;
                                //失败提示
                                this.$message({
                                    message: '删除成功'+ result.message,
                                    type: 'error'
                                });
                                this.page =1; //删除后跳转第一页
                                //从新获取数据
                                this.getProducts();
                            }
                        })
                        .catch(result=>{
                            alert("系统错误");
                            this.getProducts();
                            this.listLoading = false;
                        })

                }).catch(() => {

                });
            }
        },
		mounted() {
			this.getProducts();
		}
	}

</script>

<style scoped>
</style>